﻿using System.Reflection;
using System.Windows.Media.Animation;
using OpenLightGroup.Common.ApplicationServices;
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace Examples.Controls
{
    public partial class ErrorNotificationControl : UserControl
    {
        private HealthReportingAgent EventAgent;
        private bool _isNotificationShown = false;

        public ErrorNotificationControl()
        {
            this.InitializeComponent();

            this.Loaded += new RoutedEventHandler(ErrorNotificationControl_Loaded);

            if (!DesignerProperties.IsInDesignTool)
            {


                this.EventAgent = new HealthReportingAgent();

                this.EventAgent.LatestExceptionsChanged += new EventHandler<NewExceptionsEventArgs>(EventAgent_LatestExceptionsChanged);
            }

        }

        private void ShowNotification()
        {
            if (this._isNotificationShown == false)
            {
                try
                {
                    this._isNotificationShown = true;
                    this.NotificationStoryboard.Begin();
                }
                catch (Exception ex)
                {

                    var x = ex;
                }
            }
            else
            {
                this.RefreshNotificationStoryboard.Begin();
            }
        }
        private void CloseNotification()
        {
            if (this._isNotificationShown == true)
            {
                this._isNotificationShown = false;
                this.CloseNotificationStoryboard.Begin();

            }
        }
        void EventAgent_LatestExceptionsChanged(object sender, NewExceptionsEventArgs e)
        {
            this.NumberTextBlock.Text = e.NewExceptions.ToString();

            if (e.NewExceptions > 0)
                ShowNotification();
            else
                CloseNotification();

        }

        void ErrorNotificationControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = this.EventAgent;

            if (!DesignerProperties.IsInDesignTool)
                this.EventAgent.StartPolling();
        }



        private void LayoutRoot_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.CloseNotification();
        }


    }
}